//
//  Publisher for durable subscriber 2
//

package main

import (
	"fmt"
	"os"
	"zmq"
)

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	sync, err := context.Socket(zmq.PULL)
	if err != nil {
		return err
	}
	defer sync.Close()
	err = sync.Bind("tcp://*:5564")
	if err != nil {
		return err
	}

	publisher, err := context.Socket(zmq.PUB)
	if err != nil {
		return err
	}
	defer publisher.Close()

	err = publisher.Bind("tcp://*:5565")
	if err != nil {
		return err
	}

	err = publisher.SetOptionVal(zmq.HWM, int64(1))
	if err != nil {
		return err
	}
	err = publisher.SetOptionVal(zmq.SWAP, int64(25000000))
	if err != nil {
		return err
	}

	sync.Recv(0)

	for n := 0; n < 10; n++ {
		msg := fmt.Sprintf("Update %d", n)
		err := publisher.Send([]byte(msg), 0)
		if err != nil {
			return err
		}
		zmq.Sleep(1e9)
	}
	return publisher.Send([]byte("END"), 0)
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Publisher for durable subscriber")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}
